import axois from 'axios';
import np from 'nprogress';
import qs from 'querystring';
import { Notification } from 'element-ui';

import auth from '../util/auth';

const addKey = (url) => {
  const k = Math.round(Math.random() * 100000);
  const path = url.split('?')[0];
  const query = url.split('?')[1];
  const newStr = qs.stringify({
    ...qs.parse(query),
    k,
  });
  return `${path}?${newStr}`;
};


const instance = axois.create({
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
  transformResponse: [(data) => {
    if (!data) {
      throw new Error('unexpect server error');
    }
    return data;
  }],
});

// inject x-clientInfo & x-token
instance.interceptors.request.use((config) => {
  np.start();
  console.log('request url ', config.url);
  const ret = {
    ...config,
    url: addKey(config.url),
    headers: {
      ...config.headers,
    },
  };
  return ret;
}, (err) => {
  throw new Error(err);
});

// de
instance.interceptors.response.use((response) => {
  np.done();
  if (response.config.url.indexOf('login') !== -1) {
    const { authorization } = response.headers;
    const errorStatus = JSON.parse(response.data).status === 500;
    if (authorization && !errorStatus) {
      auth.setToken(authorization);
    }
  }
  if (response.status === 200) {
    if (response.request.responseType === 'blob') {
      return response.data;
    }
    return JSON.parse(response.data);
  }
  throw new Error('后台数据异常，请稍后再试');
}, (e) => {
  np.done();
  if (e.response && e.response.data && e.response.status === 500) {
    const respData = JSON.parse(e.response.data);
    console.info('request 500: ', e.response);
    if (respData.status === 511) {
      alert('您尚未登录，请重新登录');
      window.location.hash = '/';
    } else if (respData.status === 203) {
      window.location.hash = '/';
    } else {
      Notification.error({
        title: '请求接口错误',
        dangerouslyUseHTMLString: true,
        message: `<div style="overflow:scroll;">接口地址：<br>${respData.path || e.response.config.url} <br> 接口错误:<br>${respData.message}</div>` || '请求接口数据有误，请稍后再试',
      });
    }
  }
  throw new Error('请求链接有误，请稍后再试');
});

export default instance;
